﻿Imports System.IO

Public Class Importer

    Private _callback As pixolut.BizBloxBuilderCore.AbstractRenderEngine.UpdateProgress
    Private _detail As pixolut.BizBloxBuilderCore.AbstractRenderEngine.UpdateStatus
    Private _errorDelegate As pixolut.BizBloxBuilderCore.AbstractRenderEngine.ErrorDelegate
    Private _project As BBXProject

    Public Sub New(ByVal project As BBXProject, _
                   ByVal callback As pixolut.BizBloxBuilderCore.AbstractRenderEngine.UpdateProgress, _
                   ByVal detail As pixolut.BizBloxBuilderCore.AbstractRenderEngine.UpdateStatus, _
                   ByVal errorDelegate As pixolut.BizBloxBuilderCore.AbstractRenderEngine.ErrorDelegate)
        Me._project = project
        Me._callback = callback
        Me._detail = detail
        Me._errorDelegate = errorDelegate
    End Sub

    Public Sub Import()
        Dim fileParserType As Type = Nothing
        Select Case Me._project.ProjectType
            Case BBXProject.ProjectTypes.SQL, BBXProject.ProjectTypes.SCRIPT
                Dim text As String = Me.ReadFromDisk(Me._project.Source)
                Me.HandleImportFinished(text)
            Case BBXProject.ProjectTypes.SQLDATABASE
                Dim generator As New SqlServer2005ScriptGenerator(Me._project.DatabaseServerName, Me._project.DatabaseName, Me._project.DatabaseUsername, Me._project.DatabasePassword, Me._project.DatabaseUseWindowsAuthentication)
                AddHandler generator.Finished, AddressOf Me.HandleImportFinished
                AddHandler generator.LogEvent, AddressOf LogImportEvent
                AddHandler generator.ShowError, AddressOf LogImportError
                Dim t As New System.Threading.Thread(AddressOf generator.GenerateScript)
                t.Start()
        End Select
    End Sub



#Region "Read from Disk"

    Private Function ReadFromDisk(ByVal filename As String) As String
        Dim src As StreamReader
        Dim inData As String
        src = File.OpenText(filename)
        inData = src.ReadToEnd()
        src.Close()
        Return inData.Trim()
    End Function


#End Region


#Region "Events"

    Private Sub HandleImportFinished(ByVal text As String)
        RaiseEvent ImportFinished(text)
    End Sub

    Private Sub LogImportEvent(ByVal msg As String)
        Me._detail(msg)
    End Sub

    Private Sub LogImportError(ByVal msg As String, ByVal details As String)
        Me._errorDelegate(msg, details)
    End Sub

    Public Event ImportFinished(ByVal text As String)

#End Region



End Class
